const {
    Orders
} = require('../models/ordersModel');

//获得所有订单
async function getOrders(req, res, next) {
    const {
        type = 'name', value = '', pageSize = 4, currentPage = 1
    } = req.query;
    // 总条数
    let total = await Orders.countDocuments();
    // 总页数
    let totalPages = Math.ceil(total / pageSize);

    let data = await Orders
        .find()
        .populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联
        .limit(pageSize - 0) // 设置请求的条数
        .skip((currentPage - 1) * pageSize) // 设置跳过的条数

    res.send({
        status: 1,
        data: {
            total,
            totalPages,
            data,
            pageSize,
            currentPage
        },
        message: '数据获取成功'
    })
}

//获得一个订单的详情
async function getOrderDetails(req, res, next) {
    const {
        _id
    } = req.query;
    const data = await Orders
        .findById(_id)
        .populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联

    if (data) {
        res.send({
            status: 1,
            data: data,
            message: '数据获取成功'
        })
    }
}

//获得所有申请退款的订单
async function getAllRefound(req, res, next) {
    const {
        type = 'name', value = '', pageSize = 4, currentPage = 1
    } = req.query;

    let data = await Orders
        .find({
            state: 6
        })
        .populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联
        .limit(pageSize - 0) // 设置请求的条数
        .skip((currentPage - 1) * pageSize) // 设置跳过的条数

    let list = await Orders
        .find({
            state: 6
        })

    // 总条数
    let total = await list.length;
    // 总页数
    let totalPages = Math.ceil(total / pageSize);
    res.send({
        status: 1,
        data: {
            total,
            totalPages,
            data,
            pageSize,
            currentPage
        },
        message: '数据获取成功'
    })
}

//修改订单的状态为退款
async function changeToRefound(req, res, next) {
    const {
        _id,
        state
    } = req.query;

    if (state != 2 && state != 5) {
        const data = await Orders.updateOne({
            _id
        }, {
            state: 7
        });
        if (data.nModified == 1) {
            res.send({
                status: 1,
                message: '退款成功'
            })
        }
    } else {
        const data = await Orders.updateOne({
            _id
        }, {
            state
        });
        if (data.nModified == 1) {
            res.send({
                status: 1,
                message: '修改成功'
            })

        }
    }

}

//获得销售员的订单页面
async function getOrdersBySalesmanId(req, res, next) {
    const {
        _id,
        type,
        currentPage = 1,
        pageSize = 3
    } = req.query;
    let msg;
    let value;
    switch (type) {
        //所有订单
        case "waitPay":
            value = 0;
            msg = await getOrdersByType(_id, currentPage, pageSize, value);
            break;
        case "payed":
            msg = await getAllPayedOrders(_id, currentPage, pageSize);
            break;
        case "valid":
            value = 2;
            msg = await getAllWorkedOrders(_id, currentPage, pageSize);
            break;
        case "invalid":
            value = 3;
            msg = await getOrdersByType(_id, currentPage, pageSize, value);
            break;
        case "claims":
            value = 4;
            msg = await getOrdersByType(_id, currentPage, pageSize, value);
            break;
        case "claimSuccess":
            value = 5;
            msg = await getOrdersByType(_id, currentPage, pageSize, value);
            break;
        case "refound":
            value = 6;
            msg = await getOrdersByType(_id, currentPage, pageSize, value);
            break;
        case "refoundSuccess":
            value = 7;
            msg = await getOrdersByType(_id, currentPage, pageSize, value);
            break;
        case "all":
            msg = await getALLOrdersByOneSalesman(_id, currentPage, pageSize);
            break;
    }
    res.send({
        status: 1,
        data: msg,
        message: '数据获取成功'
    })
}

//获得某销售员的所有订单
async function getALLOrdersByOneSalesman(_id, currentPage, pageSize) {
    const allData = await Orders.find({
        salesmanId: _id
    });
    const total = allData.length;
    let totalPages = Math.ceil(total / pageSize);
    const data = await Orders.find({
            salesmanId: _id
        }).populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联
        .limit(pageSize - 0) // 设置请求的条数
        .skip((currentPage - 1) * pageSize) // 设置跳过的条数

    return {
        total,
        totalPages,
        data,
        pageSize,
        currentPage
    }
}

//获得所有已支付的订单
async function getAllPayedOrders(_id, currentPage, pageSize) {
    //$ne 不等于
    // db.students.find({'name':{'$ne':'王五'},'age':{'$lt':19}})
    const allData = await Orders.find({
        salesmanId: _id,
        state: {
            '$ne': 0
        }
    });
    const total = allData.length;
    let totalPages = Math.ceil(total / pageSize);
    const data = await Orders.find({
            salesmanId: _id,
            state: {
                '$ne': 0
            }
        }).populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联
        .limit(pageSize - 0) // 设置请求的条数
        .skip((currentPage - 1) * pageSize) // 设置跳过的条数
    return {
        total,
        totalPages,
        data,
        pageSize,
        currentPage
    }
}

//获得已生效的订单（生效：2，理赔：4，理赔成功：5,退款中: 6）
async function getAllWorkedOrders(_id, currentPage, pageSize) {
    //$in 在[2,4,5,6]之间
    // db.users.find({‘age’ : {‘$in’ : [10, 22, 26]}});
    const allData = await Orders.find({
        salesmanId: _id,
        state: {
            '$in': [2, 4, 5, 6]
        }
    });
    const total = allData.length;
    let totalPages = Math.ceil(total / pageSize);
    const data = await Orders.find({
            salesmanId: _id,
            state: {
                '$in': [2, 4, 5, 6]
            }
        }).populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联
        .limit(pageSize - 0) // 设置请求的条数
        .skip((currentPage - 1) * pageSize) // 设置跳过的条数
    return {
        total,
        totalPages,
        data,
        pageSize,
        currentPage
    }
}


//获得某销售员的其他各种类型的订单
async function getOrdersByType(_id, currentPage, pageSize, value) {
    const allData = await Orders.find({
        salesmanId: _id,
        state: value
    });
    const total = allData.length;
    let totalPages = Math.ceil(total / pageSize);
    const data = await Orders.find({
            salesmanId: _id,
            state: value
        }).populate("salesmanId") //关联
        .populate("usersId") //关联
        .populate("productsId") //关联
        .limit(pageSize - 0) // 设置请求的条数
        .skip((currentPage - 1) * pageSize) // 设置跳过的条数
    return {
        total,
        totalPages,
        data,
        pageSize,
        currentPage
    }
}

//删除一个订单
async function deleteOneOrder(req, res) {
    const {
        _id
    } = req.body;
    try {
        const data = await Orders.findByIdAndDelete(_id);
        if (data) {
            res.send({
                status: 1,
                message: '删除成功'
            })
        } else {
            res.send({
                status: 0,
                message: '删除失败'
            })
        }
    } catch (error) {
        console.log('删除失败', error);
        res.send({
            status: 0,
            message: '删除失败'
        })
    }
}

module.exports = {
    getOrders,
    getOrderDetails,
    getAllRefound,
    changeToRefound,
    getOrdersBySalesmanId,
    deleteOneOrder
}